package com.bzsg.rightsManagementSystem.config.security_config


import com.bzsg.rightsManagementSystem.util.result.ErrorType
import com.bzsg.rightsManagementSystem.util.result.ResultUtil
import com.bzsg.rightsManagementSystem.write
import org.springframework.security.authentication.*
import org.springframework.security.core.AuthenticationException
import org.springframework.security.web.authentication.AuthenticationFailureHandler
import org.springframework.stereotype.Component
import java.io.IOException
import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Component
class CustomizeAuthenticationFailureHandler : AuthenticationFailureHandler {
    @Throws(IOException::class, ServletException::class)
    override fun onAuthenticationFailure(
        httpServletRequest: HttpServletRequest?,
        httpServletResponse: HttpServletResponse,
        e: AuthenticationException?
    ) {
        //返回json数据
        val result = when (e) {
            is AccountExpiredException -> {
                //账号过期
                ResultUtil.error(ErrorType.AccountExpired)
            }

            is BadCredentialsException -> {
                //密码错误
                println(e)
                ResultUtil.error(ErrorType.PasswordError)
            }

            is CredentialsExpiredException -> {
                //密码过期
                ResultUtil.error(ErrorType.CredentialsExpired)
            }

            is DisabledException -> {
                //账号不可用
                ResultUtil.error(ErrorType.Disabled)
            }

            is LockedException -> {
                //账号锁定
                ResultUtil.error(ErrorType.AccountLocked)
            }

            is InternalAuthenticationServiceException -> {
                //用户不存在
                ResultUtil.error(ErrorType.UserNoExits)
            }

            else -> {
                //其他错误
                ResultUtil.error(ErrorType.UNKNOWN)
            }
        }
        httpServletResponse.contentType = "text/json;charset=utf-8"
        httpServletResponse.write(result)
    }
}